In [ ]:
# note, you can't use 'list' as a variable, it is a python protected phrase
my_list = []
my_int_list = [1, 3, 5, 7, 10, 11]
print my_list
print my_int_list
Lists do not have to contain the same type
In [ ]:
my_mixed_list = [True, "i got", 3 + 1, "equals", 4, "goats for christmas"]
print my_mixed_list
you can even store lists into variables!
In [ ]:
my_mixed_list = [True, "i got", 3 + 1, "equals", 4, "goats for christmas"]
print "my_mixed_list = ", my_mixed_list
x = my_mixed_list
print "x = ", x
In [ ]:
# consider this: I have a list of data:
patient_data = ["Daniel", "Chen", 25, "male"]
print patient_data
How would I, for example, get only the first name? or the age?
First there are a few things to mention about indexing in python
Index | 0 | 1 | 2 | 3 |
---|---|---|---|---|
Value | Daniel | Chen | 25 | male |
In [ ]:
patient_data = ["Daniel", "Chen", 25, "male"]
# extract my first name
print "fname = ", patient_data[0]
In [ ]:
# extract the age
patient_data[2]
Lists are what we call an 'iterable', that is something that you can just go one-by-one through
Remember strings? They are also iterables
In [ ]:
string = "Coconut"
# get the first letter
string[0]
# get the second letter
string[1]
# get the first letter from the end
string[-1]
In [ ]:
# year 2014; CT 255; ID 1
censusID = "2014-255-001"
# what if we just want the year?
# we can slice!
censusID[0:4]
# since it is from the beginning we can also do the following
censusID[:4]
# both results will return a STRING 2014
In [ ]:
censusID[5:8]
censusID[9:]
Introduce yourself to 1 neighbor, get their first and last name.
Write an inequality that extracts out the first names, and test to see whether or not they are equal
In [ ]:
x = "My name is Ben DeCoudres"
y = "my neighbor's name is Michelle Hong"
print x[-13:-10] == y[-13:-5]
'''
print x[-13:-1]
print y[-13:-5]
'''
In [ ]:
# some list
lerp = [1, 3, 5, 7, 9, 22]
# append
lerp.append(4)
print lerp
In [ ]:
# pop (get the last value, and also remove from list)
print lerp.pop()
print lerp
In [ ]:
# delete second entry
del lerp[1]
print lerp
In [ ]:
# slice (just like strings)
In [ ]:
# add lists
In [ ]:
# check if something is in a list
7 in lerp
In [ ]:
# check how many elements are in a list
len(lerp)
Tuples are just like lists, except hwatever you put in there, is permanent, it cannot be changed
you might think that's weird, but an example is after you load in patient data, and you do not want any of the information accidentely changed, you can load it into a tuple to ensure what you put in stays the same
In [ ]:
# use a parenthesis instead of square bracket, everything else is the same
terp = (2, 6, 8, True, "hello")
print terp